<template>
  <div class="campus-map-container">
    <div id="map-container" class="map-box"></div>
    <div class="controls-panel">
      <div class="point-item">
        <el-tag type="success">起点:</el-tag>
        <span class="point-name">{{ mapStore.startPoint ? mapStore.startPoint.name : '未选择' }}</span>
        <el-button v-if="mapStore.startPoint" type="text" size="small" @click="clearStartPoint">清除</el-button>
      </div>
      <div class="point-item">
        <el-tag type="info">终点:</el-tag>
        <span class="point-name">{{ mapStore.endPoint ? mapStore.endPoint.name : '未选择' }}</span>
        <el-button v-if="mapStore.endPoint" type="text" size="small" @click="clearEndPoint">清除</el-button>
      </div>
      <el-button type="primary" @click="setNavigation">导航模式</el-button>
      <el-button type="primary" @click="pushpin">图钉模式</el-button>
      <el-button type="primary" @click="searchRoute">规划路线</el-button>
      <el-button @click="clearAllPointsAndRoute">清除所有</el-button>
      <el-button type="primary" @click="findcharge">显示充电桩</el-button>

      <div class="search-box">
        <el-input v-model="searchKeyword" placeholder="搜索地点"></el-input>
        <el-button type="primary" @click="placeSearch">搜索</el-button>
      </div>
    </div>
  </div>
  <div id="panel"></div>
  <InfoWindow
      :is-visible="showInfoWindow"
      :position="clickPosition"
      :ID="lostID"
      @close="handleInfoWindowClose"
      @submit="handleInfoSubmit"
  />
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useMapStore } from '@/stores/mapStore'; // 假设这是您的 Pinia store 导入路径
import { ElMessage, ElMessageBox } from 'element-plus';
import InfoWindow from './InfoWindow.vue';
import axios from 'axios'; // 假设您使用axios进行HTTP请求

// --- Pinia Store ---
const mapStore = useMapStore();

// --- 高德地图相关变量 ---
let map = null; // 地图实例
let AMap = null; // 高德地图对象，用于存储加载后的 AMap
let startMarker = null; // 起点标记
let endMarker = null;   // 终点标记
let driving = null;     // 驾车路线规划实例
let placeSearchInstance = null; // 地点搜索实例
let ispin = false;
let labelsLayer = null;
let labelsLayercharge = null;
let loca = null;
let geo = null;

const lostID = ref();
const clickPosition = ref();
const showInfoWindow = ref(false);
const searchKeyword = ref(''); // 搜索关键词
const geoData = ref(null); // 存储从数据库加载的充电桩数据

const icon = {
  type: "image", //图标类型，现阶段只支持 image 类型
  image: "https://a.amap.com/jsapi_demos/static/demo-center/marker/express2.png", //可访问的图片 URL
  size: [64, 30], //图片尺寸
  anchor: "bottom-center", //图片相对 position 的锚点，默认为 bottom-center
};

// --- 异步加载高德地图 JS API 2.0 ---
const loadAmapScript = () => {
  return new Promise((resolve, reject) => {
    if (window.AMap) {
      AMap = window.AMap;
      resolve();
      return;
    }

    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://webapi.amap.com/maps?v=2.0&key=19b72c7d05dfe5b3a710221d39eb2e51&plugin=AMap.Driving,AMap.PlaceSearch,AMap.ToolBar,AMap.Marker,AMap.Polyline,AMap.CircleMarker,AMap.Geocoder,AMap.LabelsLayer';
    script.onerror = reject;
    script.onload = () => {
      if (window.AMap) {
        AMap = window.AMap;
        resolve();
      } else {
        reject(new Error('AMap script loaded, but AMap object not found.'));
      }
    };

    window._AMapSecurityConfig = {
      securityJsCode: '9a053e7aef1ff65e5217be464b0a1a68', // 替换为您的安全密钥
    };

    document.head.appendChild(script);
  });
};

const loadLocaScript = () => {
  return new Promise((resolve, reject) => {
    if (window.Loca) {
      loca = window.Loca;
      resolve();
      return;
    }

    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = "https://webapi.amap.com/loca?v=2.0.0&key=6f025e700cbacbb0bb866712d20bb35c";
    script.onerror = reject;
    script.onload = () => {
      if (window.Loca) {
        loca = window.Loca;
        resolve();
      } else {
        reject(new Error('Loca script loaded, but Loca object not found.'));
      }
    };

    window._AMapSecurityConfig = {
      securityJsCode: '9a053e7aef1ff65e5217be464b0a1a68', // 替换为您的安全密钥
    };

    document.head.appendChild(script);
  });
};

// --- 地图初始化函数 ---
const initMap = async () => {
  try {
    await loadAmapScript();
    await loadLocaScript();

    if (!document.getElementById('map-container')) {
      console.error('地图容器 #map-container 不存在！');
      return;
    }

    map = new AMap.Map('map-container', {
      zoom: 16,
      center: [120.353950, 30.314408],
      viewMode: '3D'
    });

    labelsLayer = new AMap.LabelsLayer({
      zooms: [3, 20],
      zIndex: 1000,
      collision: true,
      allowCollision: true,
    });

    try {
      initpin();
    } catch (error) {
      console.error('图钉加载失败:', error);
    }

    map.on('click', (e) => {
      const { lnglat } = e;
      console.log(`地图被点击：经度 ${lnglat.lng}, 纬度 ${lnglat.lat}`);
      if (ispin) {
        const now = new Date();
        const timestamp = now.getTime();
        showInfoWindow.value = true;
        clickPosition.value = { lng: lnglat.lng, lat: lnglat.lat };
        lostID.value = timestamp.toString();
      } else {
        if (!mapStore.startPoint) {
          setPoint(lnglat.lng, lnglat.lat, 'start');
        } else if (!mapStore.endPoint) {
          setPoint(lnglat.lng, lnglat.lat, 'end');
        } else {
          ElMessage.warning('起点和终点均已选择，请先清除。');
        }
      }
    });

    map.addControl(new AMap.ToolBar());

    ElMessage.success('地图加载成功！');

    // eslint-disable-next-line no-undef
    loca = new Loca.Container({ map });
  } catch (error) {
    console.error('地图加载失败:', error);
    ElMessage.error('地图加载失败，请检查网络或API配置。');
  }
};

// --- 动态加载充电桩数据 ---
const findcharge = async () => {
  try {
    const response = await axios.get('http://localhost:8080/charging_pile/list'); // 替换为你的后端 API 地址
    const data = response.data;
    // 构造与原 JSON 格式一致的 geoData
    geoData.value = {
      type: 'FeatureCollection',
      features: data.map(item => ({
        type: 'Feature',
        properties: {
          name: item.name,
          address: item.address
        },
        geometry: {
          type: 'Point',
          coordinates: [parseFloat(item.longitude), parseFloat(item.latitude)]
        }
      }))
    };
    // eslint-disable-next-line no-undef
    labelsLayercharge = new Loca.LabelsLayer({ zooms: [10, 20] });
    // eslint-disable-next-line no-undef
    geo = new Loca.GeoJSONSource({ data: geoData.value });
    labelsLayercharge.setSource(geo);
    labelsLayercharge.setStyle({
      icon: {
        type: 'image',
        image: 'https://a.amap.com/Loca/static/loca-v2/demos/mock_data/charging_pile.png',
        size: [48, 75],
        anchor: 'center',
      },
      text: {
        content: (index, feat) => feat.properties.name,
        style: {
          fontSize: 12,
          fontWeight: 'normal',
          fillColor: '#5CDE8E',
          strokeColor: '#000',
          strokeWidth: 2,
        },
        direction: 'bottom',
      },
      extData: (index, feat) => feat.properties,
    });

    loca.add(labelsLayercharge);
    var normalMarker = new AMap.Marker({ offset: [70, -15] });
    var labelMarkers = labelsLayercharge.getLabelsLayer().getAllOverlays();
    for (let marker of labelMarkers) {
      marker.on('mouseover', (e) => {
        var position = e.data.data && e.data.data.position;
        if (position) {
          normalMarker.setContent('<div class="amap-info-window">地址：' + marker.getExtData().address + '</div>');
          normalMarker.setPosition(position);
          map.add(normalMarker);
        }
      });
      marker.on('mouseout', () => {
        map.remove(normalMarker);
      });
    }
    ElMessage.success('充电桩显示成功！');
  } catch (error) {
    console.error('获取充电桩数据失败:', error);
    ElMessage.error('加载充电桩数据失败，请检查后端服务。');
  }
};

const handleInfoWindowClose = () => {
  showInfoWindow.value = false;
};

const handleInfoSubmit = (formData) => {
  console.log('从弹窗接收到提交的数据:', formData);
  setpin(formData);
};

const setPoint = (lng, lat, type) => {
  const position = new AMap.LngLat(lng, lat);
  let marker;

  if (type === 'start' && startMarker) {
    map.remove(startMarker);
  } else if (type === 'end' && endMarker) {
    map.remove(endMarker);
  }

  marker = new AMap.Marker({
    position: position,
    map: map,
    icon: type === 'start' ? 'https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png' : 'https://webapi.amap.com/theme/v1.3/markers/n/mark_rs.png',
    offset: new AMap.Pixel(-10, -34)
  });

  new AMap.Geocoder().getAddress(position, (status, result) => {
    if (status === 'complete' && result.info === 'OK') {
      const name = result.regeocode.formattedAddress;
      const pointInfo = { lng, lat, name };
      if (type === 'start') {
        mapStore.setStartPoint(pointInfo);
        startMarker = marker;
      } else {
        mapStore.setEndPoint(pointInfo);
        endMarker = marker;
      }
      ElMessage.success(`${type === 'start' ? '起点' : '终点'}已设置为: ${name}`);
    } else {
      ElMessage.warning('未能获取地点名称，已设置为经纬度。');
      const pointInfo = { lng, lat, name: `${lng},${lat}` };
      if (type === 'start') {
        mapStore.setStartPoint(pointInfo);
        startMarker = marker;
      } else {
        mapStore.setEndPoint(pointInfo);
        endMarker = marker;
      }
    }
  });
};

const clearStartPoint = () => {
  console.log('清除起点按钮点击');
  if (startMarker) {
    map.remove(startMarker);
    startMarker = null;
  }
  mapStore.clearSP();
  clearRouteDisplay();
  ElMessage.info('起点已清除。');
};

const clearEndPoint = () => {
  console.log('清除终点按钮点击');
  if (endMarker) {
    map.remove(endMarker);
    endMarker = null;
  }
  mapStore.clearEP();
  clearRouteDisplay();
  ElMessage.info('终点已清除。');
};

const clearAllPointsAndRoute = () => {
  mapStore.clearPs();
  clearRouteDisplay();
  map.clearMap();
  ElMessage.info('所有点和路线已清除。');
};

const searchRoute = () => {
  if (!mapStore.startPoint || !mapStore.endPoint) {
    ElMessage.warning('请先选择起点和终点！');
    return;
  }
  if (!AMap || !map) {
    ElMessage.error('地图未初始化完成！');
    return;
  }

  clearRouteDisplay();

  if (!driving) {
    driving = new AMap.Driving({ map, panel: 'panel' });
  }

  const startLngLat = new AMap.LngLat(mapStore.startPoint.lng, mapStore.startPoint.lat);
  const endLngLat = new AMap.LngLat(mapStore.endPoint.lng, mapStore.endPoint.lat);
  driving.search(startLngLat, endLngLat, (status, result) => {
    if (status === 'complete' && result.routes) {
      ElMessage.success('路线规划成功！');
    } else {
      console.error('获取驾车数据失败：', result);
      ElMessage.error('路线规划失败: ' + result.info);
    }
  });
};

const clearRouteDisplay = () => {
  if (driving) {
    driving.clear();
  }
};

const setNavigation = () => {
  ElMessage.success('切换为导航模式');
  if (ispin) {
    ispin = false;
  }
};

const pushpin = () => {
  ElMessage.success('切换为图钉模式');
  if (!ispin) {
    ispin = true;
  }
};

const initpin = () => {
  getallpindata()
      .then(pindata => {
        if (Array.isArray(pindata)) {
          pindata.forEach((value, index) => {
            console.log(`第 ${index} 个值是: `, value);
            setpin(value);
          });
        } else {
          console.error("getallpindata did not return an array:", pindata);
        }
      })
      .catch(error => {
        console.error("Error in initpin:", error);
      });
};

const getallpindata = async () => {
  try {
    const response = await axios.post('http://localhost:8080/lost_and_found/list');
    if (response.status === 200) {
      return response.data;
    } else {
      alert('信息获取失败: ' + response.data.message);
    }
  } catch (error) {
    console.error('获取数据时发生错误:', error);
    alert('信息获取失败，请检查网络或服务器。');
  }
};

const setpin = (formdata) => {
  let labelMarker = new AMap.LabelMarker({
    name: formdata.name,
    position: [formdata.longitude, formdata.latitude],
    opacity: 1,
    zIndex: 2,
    icon: icon,
    text: {}
  });
  var content = `
    <div class='custom-info' style='padding: 15px 20px; font-family: "Segoe UI", Arial, sans-serif; max-width: 320px; background: #f9f9f9; border-radius: 10px; box-shadow: 0 4px 10px rgba(0,0,0,0.1);'>
      <h4 style='margin-top: 0; color: #2c3e50; font-size: 18px; border-bottom: 1px solid #ddd; padding-bottom: 5px;'>🧳 失物信息</h4>
      <p style='margin: 8px 0; display: flex; align-items: center;'><i class='fas fa-user' style='width: 20px; color: #3498db;'></i> <strong style='color: #555;'>发现人：</strong> ${formdata.name}</p>
      <p style='margin: 8px 0; display: flex; align-items: center;'><i class='fas fa-phone' style='width: 20px; color: #2ecc71;'></i> <strong style='color: #555;'>联系方式：</strong> ${formdata.numberphone}</p>
      <p style='margin: 8px 0; display: flex; align-items: center;'><i class='fas fa-briefcase' style='width: 20px; color: #f39c12;'></i> <strong style='color: #555;'>失物描述：</strong> ${formdata.description}</p>
      <p style='margin: 8px 0; display: flex; align-items: center;'><i class='fas fa-map-marker-alt' style='width: 20px; color: #e74c3c;'></i> <strong style='color: #555;'>坐标：</strong> (${formdata.longitude}, ${formdata.latitude})</p>
      <div style='text-align: right; margin-top: 10px;'>
        <img src='https://webapi.amap.com/images/sharp.png' style='width: 20px; height: 20px; vertical-align: middle;' alt='图标'>
      </div>
    </div>
  `;
  var infoWindow = new AMap.InfoWindow({
    isCustom: true,
    content: content,
    offset: new AMap.Pixel(16, -45),
  });
  labelMarker.on('mouseover', () => infoWindow.open(map, [formdata.longitude, formdata.latitude]));
  labelMarker.on('mouseout', () => infoWindow.close());
  labelMarker.on('click', () => {
    if (!ispin) {
      const position = labelMarker.getOptions().position;
      const lng = position[0];
      const lat = position[1];
      if (!mapStore.startPoint) {
        setPoint(lng, lat, 'start');
      } else if (!mapStore.endPoint) {
        setPoint(lng, lat, 'end');
      } else {
        ElMessage.warning('起点和终点均已选择，请先清除。');
      }
    }
  });
  labelsLayer.add(labelMarker);
  map.add(labelsLayer);
};

const placeSearch = () => {
  console.log('搜索按钮被点击了，placeSearch 函数被调用！');
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词！');
    return;
  }
  if (!AMap || !map) {
    ElMessage.error('地图未初始化完成！');
    return;
  }

  if (!placeSearchInstance) {
    placeSearchInstance = new AMap.PlaceSearch({
      map: map,
      pageSize: 5,
      pageIndex: 1,
      city: '兰州市',
    });
  }
  placeSearchInstance.search(searchKeyword.value, (status, result) => {
    if (status === 'complete' && result.info === 'OK') {
      ElMessage.success(`搜索到 ${result.poiList.pois.length} 个结果！`);
      mapStore.clearPs();
      clearRouteDisplay();
      map.clearMap();

      result.poiList.pois.forEach(poi => {
        new AMap.Marker({
          map: map,
          position: [poi.location.lng, poi.location.lat],
          title: poi.name
        }).on('click', () => {
          ElMessageBox.confirm(
              `是否将 "${poi.name}" 设置为起点或终点?`,
              '选择',
              {
                distinguishCancelAndClose: true,
                confirmButtonText: '设为起点',
                cancelButtonText: '设为终点',
                type: 'info',
              }
          )
              .then(() => setPoint(poi.location.lng, poi.location.lat, 'start'))
              .catch((action) => action === 'cancel' && setPoint(poi.location.lng, poi.location.lat, 'end'));
        });
      });
      map.setFitView();
    } else {
      console.error('地点搜索失败：', result);
      ElMessage.error('地点搜索失败: ' + result.info);
    }
  });
};

onMounted(() => {
  initMap();
});

onUnmounted(() => {
  if (map) {
    map.destroy();
    map = null;
    AMap = null;
  }
});
</script>

<style scoped>
.campus-map-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.map-box {
  flex-grow: 1;
  height: 80%;
  width: 100%;
}

.controls-panel {
  padding: 15px;
  background: #f5f7fa;
  border-top: 1px solid #ebeef5;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  justify-content: flex-start;
}

.point-item {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-right: 15px;
}

.point-name {
  font-weight: bold;
  color: #333;
}

.search-box {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

#panel {
  position: fixed;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 10px;
  right: 10px;
  width: 280px;
}

#panel .amap-call {
  background-color: #009cf9;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}

#panel .amap-lib-driving {
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  overflow: hidden;
}
</style>